package com.pig.config;

import com.pig.dao.AdminDao;
import com.pig.pojo.user.Admin;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;


@Component
public class ManageShiroRealm extends AuthorizingRealm {
    @Autowired
    private AdminDao adminDao;

    /*
    * 授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }



    /*
    * 认证和封装*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取登录用户信息（用户名，密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();

        //基于用户名查询数据库中的用户对象
        Admin admin = adminDao.findUserByAdminName(username);

        //检测用户是否存在
        if (admin == null)
            throw new UnknownAccountException();
        //封装用户信息并返回


        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                admin,//用户身份
                admin.getPassword(),//凭证-已加密
                getName());


        return info;
    }




    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher cmatcher = new HashedCredentialsMatcher();
        cmatcher.setHashAlgorithmName("MD5");
        cmatcher.setHashIterations(1);
        return cmatcher;
    }

}

